<script setup lang="ts">
import { reactive, ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
// @ts-ignore
import { ReadClients, WriteClients } from '@/Urls/AxiosHelper'

const router = useRouter()
const route = useRoute()
const readClient = ReadClients[3]
const writeClient = WriteClients[3]

const routeBomNumber = computed(() => (route.query.bomNumber as string) || '')

// 表单数据
const form = reactive({
  id: '',
  bomNumber: routeBomNumber.value,
  version: '',
  productName: '',
  productNumber: '',
  specificationModel: '',
  unit: '',
  isDefaultBom: false,
  dailyOutput: 0,
  remarks: '',
  processRouteNumber: ''
})

// 表单验证规则
const rules = {
  version: [{ required: true, message: '请选择版本', trigger: 'change' }],
  dailyOutput: [{ required: true, message: '请输入日产量', trigger: 'blur' }]
}

// 版本选项
const versionOptions = ['1.0', '1.1', '1.2', '2.0', '2.1']

// 其他状态
const loading = ref(false)
const formRef = ref()

// 生成GUID
function generateGuid(): string {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0
    const v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}

// 按 BomNumber 查询基础信息并反填
async function fetchBaseInfoByBomNumber(bomNumber: string) {
  if (!bomNumber) {
    console.log('BomNumber为空，跳过数据获取')
    return
  }
  
  try {
    loading.value = true
    const res = await readClient.get('/productread/api/Bom/GetBomInfoByBomNumber', { params: { BomNumber: bomNumber } })
    
    const payload = res?.data
    const item = payload?.data || payload || {}
    
    // 根据返回的属性进行反填
    form.id = item.id || form.id
    form.bomNumber = item.bomNumber || form.bomNumber
    form.version = item.bomVersion || item.version || form.version
    form.productName = item.productName || form.productName
    form.productNumber = item.productNumber || form.productNumber
    form.specificationModel = item.specificationModel || form.specificationModel
    form.unit = item.unit || form.unit
    form.isDefaultBom = item.isDefaultBom ?? form.isDefaultBom
    form.dailyOutput = item.dailyOutput ?? form.dailyOutput
    form.remarks = item.remarks || form.remarks
    form.processRouteNumber = item.processRouteNumber || form.processRouteNumber
    
  } catch (error) {
    console.error('获取BOM基础信息失败:', error)
    ElMessage.error('获取BOM基础信息失败')
  } finally {
    loading.value = false
  }
}

// 保存
async function handleSave() {
  try {
    await formRef.value.validate()
    
    loading.value = true
    
    const payload = {
      id: form.id || generateGuid(),
      bomNumber: form.bomNumber,
      bomVersion: form.version,
      productName: form.productName,
      productNumber: form.productNumber,
      specificationModel: form.specificationModel,
      unit: form.unit,
      isDefaultBom: form.isDefaultBom,
      dailyOutput: form.dailyOutput,
      remarks: form.remarks,
      processRouteNumber: form.processRouteNumber,
    }
    
    await writeClient.post('/productwrite/api/Bom/UpdateBom', payload)
    
    ElMessage.success('保存成功')
    router.push({ name: 'BomDetail', query: { bomNumber: form.bomNumber } })
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    loading.value = false
  }
}

// 取消
function handleCancel() {
  router.push({ name: 'BomInfo' })
}

// 进入或路由变化时拉取基础信息
watch(routeBomNumber, (bn) => { if (bn) fetchBaseInfoByBomNumber(bn) }, { immediate: true })
</script>

<template>
  <div class="bom-edit-container" v-loading="loading">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>BOM编辑</h2>
    </div>

    <!-- 基础信息卡片 -->
    <el-card class="info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">基础信息</span>
        </div>
      </template>
      
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="form-container">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="BOM编号" prop="bomNumber">
              <el-input v-model="form.bomNumber" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="版本" prop="version">
              <el-select v-model="form.version" placeholder="请选择版本" style="width: 100%">
                <el-option
                  v-for="version in versionOptions"
                  :key="version"
                  :label="version"
                  :value="version"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="产品编号" prop="productNumber">
              <el-input v-model="form.productNumber" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规格型号" prop="specificationModel">
              <el-input v-model="form.specificationModel" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="是否默认BOM" prop="isDefaultBom">
              <el-switch v-model="form.isDefaultBom" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="日产量" prop="dailyOutput">
              <el-input-number v-model="form.dailyOutput" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工艺编号" prop="processRouteNumber">
              <el-input v-model="form.processRouteNumber" disabled />

            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="form.remarks"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="action-card" shadow="hover">
      <div class="action-buttons">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="loading">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.bom-edit-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.info-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.form-container {
  padding: 20px 0;
}

.action-card {
  margin-top: 20px;
  border-radius: 8px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 20px 0;
}
</style>

